import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpStatus,
  ServiceUnavailableException,
  Inject,
  HttpException,
} from '@nestjs/common';
import { WINSTON_MODULE_PROVIDER } from 'nest-winston';
import { getReqMainInfo } from 'utils/common/getReqMainInfo';
import { Logger } from 'winston';
@Catch()
export class AllExceptionFilter implements ExceptionFilter {
  constructor(
    @Inject(WINSTON_MODULE_PROVIDER) private readonly logger: Logger,
  ) {}

  catch(exception: Error, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse();
    const request = ctx.getRequest();
    const status =
      exception instanceof HttpException
        ? exception.getStatus()
        : HttpStatus.INTERNAL_SERVER_ERROR;
    let msg =
      exception.message || (status >= 500 ? 'Service Error' : 'Client Error');
    if (
      Object.prototype.toString.call(response) === '[object Object]' &&
      response.message
    ) {
      msg = response.message;
    }

    // 记录日志（错误消息，错误码，请求信息等）
    this.logger.error('AllExceptionFilter', {
      status,
      req: getReqMainInfo(request),
      res: (exception as any)?.response?.data ?? {},
    });
    // 非 HTTP 标准异常的处理。
    response.status(HttpStatus.SERVICE_UNAVAILABLE).send({
      code: HttpStatus.SERVICE_UNAVAILABLE,
      isSuccess: false,
      status: false,
      timestamp: new Date().toISOString(),
      path: request.url,
      msg: new ServiceUnavailableException().getResponse(),
    });
  }
}
